package com.zyk.leetcode;

import java.util.Arrays;

/**
 * @author zhangsan
 * @date 2021/5/2 13:30
 */
public class C59 {


    public static int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        process(0, 0, n - 1, n - 1, 1, matrix);
        return matrix;
    }

    // r1,c1 左上角
    // r2,c2 右下角
    // start 左上角开始填的值
    public static void process(int r1, int c1, int r2, int c2, int start, int[][] m) {
        if (r1 > r2) {
            return;
        }
        for (int col = c1; col <= c2; col++) {  // 最上一行
            m[r1][col] = start++;
        }
        for (int row = r1 + 1; row <= r2; row++) {  // 最右一列
            m[row][c2] = start++;
        }
        for (int col = c2 - 1; col >= c1; col--) {  // 最下一行
            m[r2][col] = start++;
        }
        for (int row = r2 - 1; row >= r1 + 1; row--) {  // 最左一列
            m[row][c1] = start++;
        }
        process(r1 + 1, c1 + 1, r2 - 1, c2 - 1, start, m);
    }

    // 对数器方法
    public static int[][] generateMatrix2(int n) {
        if (n == 1) {
            return new int[][]{{
                    1
            }};
        } else if (n == 2) {
            return new int[][]{
                    {1, 2},
                    {4, 3}
            };
        } else if (n == 3) {
            return new int[][]{
                    {1, 2, 3},
                    {8, 9, 4},
                    {7, 6, 5},
            };
        } else if (n == 4) {
            return new int[][]{
                    {1, 2, 3, 4},
                    {12, 13, 14, 5},
                    {11, 16, 15, 6},
                    {10, 9, 8, 7},
            };
        } else if (n == 5) {
            return new int[][]{
                    {1, 2, 3, 4, 5},
                    {16, 17, 18, 19, 6},
                    {15, 24, 25, 20, 7},
                    {14, 23, 22, 21, 8},
                    {13, 12, 11, 10, 9},
            };
        } else {
            return new int[0][0];
        }
    }


    // for test
    public static void main(String[] args) {
        int n = 3;
        int[][] ans1 = generateMatrix(n);
        int[][] ans2 = generateMatrix2(n);
        System.out.println(isEqual(ans1, ans2));

        for (int[] nums : ans1) {
            System.out.println(Arrays.toString(nums));
        }
    }

    private static boolean isEqual(int[][] m1, int[][] m2) {
        if(m1 == null || m2 == null) {
            if(m1 != null || m2 != null) return false;
        }
        if(m1.length != m2.length || m1[0].length != m2[0].length) return false;
        int R = m1.length, C = m1[0].length;
        for (int r = 0; r < R; r++) {
            for (int c = 0; c < C; c++) {
                if(m1[r][c] != m2[r][c]) return false;
            }
        }
        return true;
    }

}
